<style>
.tree {
  /*margin-top: 42px;*/
  /* border: 1px solid #d7dde4; */
  max-height: 600px;
  overflow-y: scroll;
}

.ztree li span {
  padding-bottom: 25px;
  /*margin-top: 20px;*/
  /*margin-bottom: 20px;*/
  /*border: 1px solid #ffffff;*/
  /*background: #f0f6e4;*/
  /*width:220px;height:360px;*/
  /*overflow-y:scroll;*/
  /*overflow-x:auto;*/
}
</style>

<template>
  <Row class="layout-content-body">
    <!-- <Col span="4" class="tree">
    <div class="bg left tree">
        <ul id="treeD" class="ztree"></ul>
    </div>
    </Col>-->
    <Col span="24">
      <!-- <dtable :columns="columns" :dataAll="dataAll" :dataShow="dataShow" :loading="loading" director add delCheck assign check op @refresh="getall()" @add="add" @del="del" @edit="edit" @delCheck="delCheck" @assign="assign" @director="director"></dtable> -->
      <BaseTable
        :columns="columns"
        :data="dataAll"
        :total="total"
        op ck pager back
        @refresh="getall()"
        @add="add"
        @del="del"
        @edit="edit"
        @delCheck="delCheck"
        @assign="assign"
        @page-change="pageChange"
      />
    </Col>
    <Modal
      v-model="editData"
      title="学院信息"
      :mask-closable="false"
      class="editm"
      @on-ok="asyncOK"
      @on-cancel="asyncCancel" >
      <Form ref="editForm" :model="formItem" :label-width="80" :rules="ruleValidate">
        <Form-item label="名称" prop="Name">
          <Input v-model="formItem.Name" placeholder="请输入" @on-enter="asyncOK()"></Input>
        </Form-item>
        <Form-item label="状态" prop="Status">
          <Radio-group v-model.number="formItem.Status" disabled>
            <Radio :label="1">启用</Radio>
            <Radio :label="0">停用</Radio>
          </Radio-group>
        </Form-item>
        <Form-item label="说明" prop="Remark">
          <Input
            v-model="formItem.Remark"
            type="textarea"
            :autosize="{minRows: 2,maxRows: 5}"
            placeholder="请输入..."
          ></Input>
        </Form-item>
      </Form>
    </Modal>
    <Modal v-model="directorFlag" :title="directorTitle" :mask-closable="false" class="editm">
      <Table stripe border highlight-row :columns="deptuserColumn" :data="directorData"/>
    </Modal>
  </Row>
</template>

<script>
// import '@s/plugins/zTree/js/jquery.ztree.core';
// import '@s/plugins/zTree/js/jquery.ztree.excheck';
// import '@s/plugins/zTree/js/jquery.ztree.exedit';
// import '@s/plugins/zTree/js/jquery.ztree.exhide';
// import 'font-awesome/css/font-awesome.css';
// import '@s/plugins/zTree/css/awesomeStyle/awesome.css';
import { mapMutations, mapGetters, mapState } from "vuex";
import BaseTable from "@/components/table/table"; // 采用biztable
// import $ from "jquery";
export default {
  components: {
    BaseTable
  },
  data() {
    return {
      loading: false, // 数据刷新遮罩层
      columns: [
        {
          title: "名称",
          key: "Name",
          sortable: true
        },
        {
          title: "专业编号",
          key: "Code"
        },
        {
          title: "所属学院",
          key: "DeptName",
          width: 280,
          sortable: true
        },
        {
          title: "状态",
          key: "Status",
          sortable: true,
          render: (h, {row}) => {
              return h('span', {}, row.Status === 1 ? '启用':'禁用')
          }
        }
      ], // 表格样式
      dataAll: [], // 表格数据来源
      dataShow: true, // 是否显示表格数据查看表单
      editData: false, // 显示编辑表单
      formItem: {
        Name: "",
        Pid: 0,
        Pname: "顶级部门",
        OrgId: "",
        OrgName: "",
        Status: 1,
        Remark: ""
      }, // 数据编辑表单
      ruleValidate: {
        Name: [
          {
            required: true,
            message: "账号不能为空",
            trigger: "blur"
          }
        ],
        Pname: [
          {
            required: true,
            message: "名称不能为空",
            trigger: "blur"
          }
        ]
        //          Pid: [
        //            {required: true, message: '必须选择上级部门', trigger: 'change'},
        //          ],
      }, // 数据编辑表单验证规则
      addid: true, // true为修改模式，false为添加模式
      treeData: [],
      total: 0,
      setting: {
        view: {
          selectedMulti: false
        },
        check: {
          enable: false
        },
        data: {
          simpleData: {
            enable: true,
            rootPId: 0
          }
        },
        edit: {
          enable: true,
          showRemoveBtn: false,
          showRenameBtn: false
        },
        callback: {
          beforeDrag: this.beforeDrag,
          beforeDrop: this.beforeDrop
        }
      },
      zNodes: [],
      directorFlag: false,
      directorData: [],
      deptuserColumn: [
        {
          type: "index",
          width: 60
        },
        {
          title: "名称",
          key: "Name",
          sortable: true
        },
        // {
        //   title: "名称",
        //   key: "Remark",
        //   sortable: true
        // },
        {
          title: "姓名",
          key: "Abbr",
          sortable: true
        },
        {
          title: "操作",
          render: (h, { row }) => {
            return h(
              "Button",
              {
                props: {
                  size: "small",
                  type: "primary"
                },
                on: {
                  click: () => {
                    // this.$Message.info(row.Id);
                    // console.log(row);
                    this.$api
                      .SetDeptDirector({
                        DeptId: this.deptTemp.Id,
                        UserId: row.Id
                      })
                      .then(res => {
                        if (res.code === 0) {
                          this.directorFlag = false;
                          this.$Message.success(
                            `已将${row.Abbr}设置为${this.deptTemp.Name}的主管！`
                          );
                        }
                      });
                  }
                }
              },
              "设置为主管"
            );
          }
        }
      ],
      deptName: "",
      deptTemp: {},
      pgData: {
        searchKey: "", // 过滤关键字，预留，暂未使用， String
        pagesize: 10, // sql limit 关键字, 分页查询使用 Number
        page: 1, // sql offset 关键字, 分页查询使用 Number
        sortby: ["Ctime"], // sql 排序关键字， eg. seq  Array [String, String ...]
        order: ["asc"], // sql 排序关键字， eg. asc, desc 只能从这里个中获取，且和sortby对应  Array [String, String ...]
        fields: [], // 返回的字段 Array [String, String ...]
        query: {} // 其它查询条件, 如 Id = 1, 表示为 query.Id = 1
      }
    };
  },
  computed: {
    // ...mapState(['isLogin', 'captchaUrl', 'cptId', 'msg', 'userInfo']),
    state() {
      return this.$store.state.app;
    },
    //      父部门
    parentRes() {
      let pr = [];
      // pr.push({
      //   Id:"0",
      //   Name: "顶级部门"
      // })
      for (let e in this.dataAll) {
        pr.push({
          Name: this.dataAll[e].Name,
          Id: this.dataAll[e].Id
        });
      }
      return pr;
    },

    directorTitle() {
      return `变更${this.deptName}主管`;
    }
  },
  watch: {},
  mounted() {
    this.getall();
  },
  methods: {
    pageChange(pagedata) {
        // console.log(pagedata)
        this.pgData.pagesize = pagedata.pagesize
        this.pgData.page = pagedata.current
        this.getall()
    },
    director(rows) {
      // console.log(rows)
      if (rows.length && rows.length !== 1) {
        this.$Message.error("请选择一行！");
        return;
      }
      this.deptName = rows[0]["Name"];
      this.deptTemp = rows[0];
      this.$api
        .GetUserByDept({
          Id: rows[0].Id
        })
        .then(res => {
          if (res.code === 0) {
            console.log(res.Data);
            this.directorData = res.Data;
            this.directorFlag = true;
          }
        });
    },
    beforeDrop(treeId, treeNodes, targetNode, moveType) {
      console.log(treeNodes);
      console.log(targetNode);
      // return targetNode ? targetNode.drop !== false : true;
      return !(
        targetNode == null ||
        (moveType !== "inner" && !targetNode.parentTId)
      );
    },
    beforeDrag(treeId, treeNodes) {
      for (var i = 0, l = treeNodes.length; i < l; i++) {
        if (treeNodes[i].drag === false) {
          return false;
        }
      }
      return true;
    },
    //      改变页码
    getall() {
      this.loading = true;
      this.$api.GetAllMajors(this.pgData).then(
        res => {
          if (!res.error) {
            this.dataAll = res.Data.list;
            this.total = res.Data.count;
            // this.zNodes = res.Data.treedata;
            // $.fn.zTree.init($("#treeD"), this.setting, this.zNodes);
          } else {
            this.$Message.error(res.message);
          }
        },
        err => {
          if (err) {
            this.$Message.error(err, 4);
          }
        }
      );
      setTimeout(() => {
        this.loading = false;
      }, 500);
    },
    getOrganization() {
      this.spinShow = true;
      this.$api.getOrganizationList().then(
        res => {
          if (!res.error) {
            this.org = res.Data;
          } else {
            this.$Message.error(res.message);
          }
        },
        err => {
          if (err) {
            this.$Message.error(err, 4);
          }
        }
      );
    },
    edit(index) {
      this.addid = true;
      this.formItem = index;
      this.editData = true;
    },
    add() {
      this.addid = false;
      this.$refs["editForm"].resetFields();
      this.formItem.OrgId = this.state.userInfo.Organization.Id;
      this.editData = true;
    },
    asyncOK() {
      this.$refs["editForm"].validate(valid => {
        if (valid) {
          if (this.addid) {
            this.$api.UpdateDept(this.formItem).then(
              res => {
                if (!res.error) {
                  this.getall();
                  this.$Message.success(res.message);
                } else {
                  this.$Message.error(res.message, 4);
                }
              },
              err => {
                if (err) {
                  this.$Message.error(err, 4);
                }
              }
            );
          } else if (!this.addid) {
            this.$api.AddDept(this.formItem).then(
              res => {
                if (!res.error) {
                  this.getall();
                  this.$Message.success(res.message);
                } else {
                  this.$Message.error(res.message, 4);
                }
              },
              err => {
                if (err) {
                  this.$Message.error(err, 4);
                }
              }
            );
          }
          setTimeout(() => {
            this.editData = false;
          }, 1000);
        } else {
          this.$Message.error("表单验证失败!");
        }
      });
      this.editData = false;
      this.$refs["editForm"].resetFields();
    },
    asyncCancel() {
      this.getall();
      this.$refs["editForm"].resetFields();
    },
    del(row) {
      this.$api.DeleteDept(row).then(
        res => {
          if (!res.error) {
            this.getall();
            this.$Message.success(res.message);
          } else {
            this.$Message.error(res.message, 4);
          }
        },
        err => {
          if (err) {
            this.$Message.error(err, 4);
          }
        }
      );
    },
    delCheck(row) {
      this.$api.DeleteDepts(row).then(
        res => {
          if (!res.error) {
            this.getall();
            this.$Message.success(res.message);
          } else {
            this.$Message.error(res.message, 4);
          }
        },
        err => {
          if (err) {
            this.$Message.error(err, 4);
          }
        }
      );
    },
    assign() {
      let treeObj = $.fn.zTree.getZTreeObj("treeD");
      let tee = treeObj.transformToArray(treeObj.getNodes());
      console.log(tee);
      this.$api.AssignUserDept(tee).then(
        res => {
          if (!res.error) {
            this.$Message.success(res.message);
          } else {
            this.$Message.error(res.message, 4);
          }
        },
        err => {
          if (err) {
            this.$Message.error(err, 4);
          }
        }
      );
    }
  }
};
</script>
